import ScreenFit from "./ScreenFit";

export default class ScreenShot {

    /**
     * 返回像素数组
     */
    static shotToPixelsAndSpriteFrame() {
        let camera = null;
        let cameraNode = cc.Canvas.instance.node.getChildByName('ShotCamera');
        if (cameraNode) {
            console.log('找到截屏摄像机');
            camera = cameraNode.getComponent(cc.Camera);
        } else {
            console.log('创建截屏摄像机');
            cameraNode = new cc.Node('ShotCamera');
            cc.Canvas.instance.node.addChild(cameraNode);
            camera = cameraNode.addComponent(cc.Camera);
        }
        camera.cullingMask = 0xffffffff;
        let width = ScreenFit.screenSize.width;
        let height = ScreenFit.screenSize.height;
        let gl = cc.game['_renderContext'];
        let texture = new cc.RenderTexture();
        texture.initWithSize(width, height, gl.STENCIL_INDEX8);
        camera.targetTexture = texture;
        camera.render(cameraNode.parent);
        let data = texture.readPixels();
        //pixels转SpriteFrame
        let canvas = document.createElement('canvas');
        let ctx = canvas.getContext('2d');
        canvas.width = width;
        canvas.height = height;
        let rowBytes = width * 4;
        for (let row = 0; row < height; row++) {
            let srow = height - 1 - row;
            let imageData = ctx.createImageData(width, 1);
            let start = srow * width * 4;
            for (let i = 0; i < rowBytes; i++) {
                imageData.data[i] = data[start + i];
            }
            ctx.putImageData(imageData, 0, row);
        }
        let dataURL = canvas.toDataURL("image/jpeg");
        let img = document.createElement("img");
        img.src = dataURL;
        let tex = new cc.Texture2D();
        tex.initWithElement(img);
        let spriteFrame = new cc.SpriteFrame(tex);
        return { spriteFrame: spriteFrame, data: data };
    }

}
